package com.lzx.iteam;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.baidu.mapapi.model.LatLng;
import com.lzx.iteam.adapter.CRMEditAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.*;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.CRMCreateMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.widget.selectdate.OnWheelScrollListener;
import com.lzx.iteam.widget.selectdate.WheelView;
import com.lzx.iteam.widget.selectdate.adapter.NumericWheelAdapter;
import com.lzx.iteam.util.*;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 08月 02日
 * Time: 上午10:08
 *
 * @QQ : 1234567890
 * **********************************
 */
public class CRMCreateEditActivity extends MyBaseActivity implements View.OnClickListener {

    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.crm_edit_list)
    private ListView mListView;

    /**
     * 页面类型
     * 1:新建公海
     * 2:编辑公海
     * 3:线索转成机会
     * 4:新建机会
     * 5:编辑机会
     * 6:新建客户
     * 7:机会转为客户
     */
    private int mFlag;

    /**
     * 所属类型:
     * 0.公海(默认)
     * 1.线索库
     * 2.机会库
     * 3.客户库
     */
    private int mType;

    private String mGroupId;
    private String mClueId;
    private String mChanceId;
    private String mClientId;
    private AddressData mAddressBean;
    private CRMChanceBean mCrmChanceBean;

    private WheelView year;
    private WheelView month;
    private WheelView day;
    private Calendar c;
    private int curYear;
    private int curMonth;
    private int curDate;
    private long date;  //时间戳


    private Dialog mWaitDialog;
    private CRMEditAdapter mAdapter;
    private ArrayList<CRMDetailBean> mListData = new ArrayList<CRMDetailBean>();
    private HashMap<String, String> hashMap = new HashMap<String, String>();


    private static final int SELECT_STATUS = 10000;         // 跟进状态
    private static final int SELECT_SEX = 10001;            // 性别
    private static final int SELECT_SOURCE = 10002;         // 线索来源
    private static final int SELECT_REMARK = 10003;         // 备注
    private static final int SELECT_STAGE = 10004;          // 销售阶段
    private static final int SELECT_CHANCE_TYPE = 10005;    // 机会类型
    private static final int SELECT_CHANCE_SOURCE = 10006;  // 机会来源
    private static final int SELECT_CONTACT = 10007;        // 新建机会时创建联系人
    private static final int SELECT_INDUSTRY = 10008;       // 行业
    private static final int SELECT_CLIENT_LEVEL = 10009;   // 客户级别


    private static final int GET_LOCCTION = 20001;          // 获取经纬度
    private static final int CREATE_PUBLIC_CRM = 30001;     // 创建公海
    private static final int EDIT_PUBLIC_CRM = 30002;       // 编辑公海
    private static final int TO_CHANCE_CRM = 30003;         // 线索转为销售机会
    private static final int EDIT_CHANCE_CRM = 30004;       // 编辑机会
    private static final int CREATE_CLIENT_CRM = 30005;     // 创建客户
    private static final int CONVERT_CLIENT_CRM = 30006;     // 转换给客户


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CREATE_PUBLIC_CRM:
                    if (msg.arg1 == 0) {
                        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(CRMCreateEditActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        CRMLibraryListData listData = (CRMLibraryListData) msg.obj;
                        if (mType == 2) {//创建机会时添加联系人
                            if (StringUtil.isEmpty(mChanceId)) {
                                Intent chance = new Intent();
                                chance.putExtra("action_type", 3);
                                chance.putExtra("clue_id", listData.get_id());
                                chance.putExtra("contact_name", listData.getName());
                                setResult(RESULT_OK, chance);
                                finish();
                            } else {//  在机会详情部分添加联系人
                                    Intent back = new Intent();
                                    back.putExtra("contact", listData);
                                    setResult(RESULT_OK, back);
                                    finish();

                            }

                        } else if (mType == 3) {
                            if (StringUtil.isEmpty(mClientId)) {
                                Intent client = new Intent();
                                client.putExtra("action_type", 6);
                                client.putExtra("clue_id", listData.get_id());
                                client.putExtra("contact_name", listData.getName());
                                setResult(RESULT_OK, client);
                                finish();
                            }
                        } else if (mType == 0) {// 新建公海线索
                            Intent intent = new Intent(mActivity, CRMLibraryActivity.class);
                            intent.putExtra("type", Constants.CRM_PUBLIC_CLUE);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();
                        }
                    } else {
                        Toast.makeText(CRMCreateEditActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case EDIT_PUBLIC_CRM:
                    if (msg.arg1 == 0) {
                        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(CRMCreateEditActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        Intent edit = new Intent();
                        edit.putExtra("crm_data", mListData);
                        Bundle bundle = new Bundle();
                        bundle.putString("email",hashMap.get("邮箱"));
                        bundle.putString("address",hashMap.get("地址"));
                        bundle.putString("longitude",mAddressBean.getLongitude()+ "");
                        bundle.putString("latitude",mAddressBean.getLatitude()+ "");
                        edit.putExtra("detail",bundle);
                        setResult(RESULT_OK, edit);
                        finish();
                    } else {
                        Toast.makeText(CRMCreateEditActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case TO_CHANCE_CRM:
                case CREATE_CLIENT_CRM:
                    if (msg.arg1 == 0) {
                        //线索转为机会,跳到线索列表 //新建机会 跳转到机会列表  // 新建客户 跳转到客户列表
                        Intent intent = new Intent(mActivity, CRMLibraryActivity.class);
                        intent.putExtra("type", mType);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(CRMCreateEditActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case EDIT_CHANCE_CRM:
                    if (msg.arg1 == 0) {
                        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(CRMCreateEditActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                       /* mCrmChanceBean.setChance_name(hashMap.get("机会名称"));
                        mCrmChanceBean.setMarket_amount(Integer.parseInt(hashMap.get("销售金额")));
                        mCrmChanceBean.setMarket_stage(Integer.parseInt(hashMap.get("销售阶段")));
                        mCrmChanceBean.setStatement_date(date + "");
                        if (!"-1".equals(hashMap.get("机会类型"))) {
                            mCrmChanceBean.setChance_type(Integer.parseInt(hashMap.get("机会类型")));
                        }
                        if (!"-1".equals(hashMap.get("机会来源"))) {
                            mCrmChanceBean.setChance_source(Integer.parseInt(hashMap.get("机会来源")));
                        }

                        mCrmChanceBean.setRemark(hashMap.get("备注"));*/
                        Intent edit = new Intent();
//                        edit.putExtra("crm_data", mCrmChanceBean);
                        setResult(RESULT_OK, edit);
                        finish();
                    } else {
                        Toast.makeText(CRMCreateEditActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case CONVERT_CLIENT_CRM:
                    if (msg.arg1 == 0) {
                        if (mFlag == 7) {
                            showNoticeDlg(1, "机会成功转成客户,请您进入\n【客户】进行操作");
                        }
                    }else{
                        Toast.makeText(CRMCreateEditActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.crm_edit_layout);
    }

    @Override
    public void initListener() {
        mTvRight.setOnClickListener(this);
        mLayoutBack.setOnClickListener(this);
    }

    @Override
    public void initData() {

        Intent intent = getIntent();
        mFlag = intent.getIntExtra("action_type", 1);
        mType = intent.getIntExtra("type", 0);
        mTvRight.setText("保存");
        mGroupId = intent.getStringExtra("group_id");
        switch (mFlag) {
            case 1:
                mTvTitle.setText("新建线索");
                mChanceId = intent.getStringExtra("chance_id");
                mListData.add(new CRMDetailBean(1, "基本信息(必填)"));
                mListData.add(new CRMDetailBean("姓名", "", 1));
                mListData.add(new CRMDetailBean("手机", "", 1));

                mListData.add(new CRMDetailBean(1, "基本信息(选填)"));
                mListData.add(new CRMDetailBean(3, "性别", 0));
                mListData.add(new CRMDetailBean("公司", ""));
                mListData.add(new CRMDetailBean("部门", ""));
                mListData.add(new CRMDetailBean("职务", ""));

                mListData.add(new CRMDetailBean(1, "联系信息(选填)"));
                mListData.add(new CRMDetailBean("电话", ""));
                mListData.add(new CRMDetailBean("邮箱", ""));
                mListData.add(new CRMDetailBean(4, "地址", ""));
                mListData.add(new CRMDetailBean("邮编", ""));

                mListData.add(new CRMDetailBean(1, "其他信息(选填)"));
                mListData.add(new CRMDetailBean(5, "线索来源", -1));
                mListData.add(new CRMDetailBean(6, "备注", ""));
                mListData.add(new CRMDetailBean(-1, ""));
                break;
            case 2:
                mTvTitle.setText("编辑资料");
                mClueId = intent.getStringExtra("clue_id");
                mListData = (ArrayList<CRMDetailBean>) intent.getSerializableExtra("crm_data");
                mAddressBean = (AddressData) intent.getSerializableExtra("address");
                for (int i = 0; i < mListData.size(); i++) {
                    CRMDetailBean data = mListData.get(i);
                    if (!StringUtil.isEmpty(data.getTitle()) && data.getTitle().equals("最新活动记录时间")) {
                        mListData.remove(i);
                    }
                }
                mListData.add(new CRMDetailBean(-1, ""));
                break;
            case 3:
                mTvTitle.setText("线索转成机会");
                mTvRight.setText("转换");
                mClueId = intent.getStringExtra("clue_id");
                mListData.add(new CRMDetailBean(1, "基本信息(必填)"));
                mListData.add(new CRMDetailBean("机会名称", "", 1));
                mListData.add(new CRMDetailBean("销售金额", "", 1));
                mListData.add(new CRMDetailBean(7, "销售阶段", 0));
                mListData.add(new CRMDetailBean(8, "结单日期", 0));
                mListData.add(new CRMDetailBean("联系人", true,intent.getStringExtra("contact_name")));

                mListData.add(new CRMDetailBean(1, "其他信息(选填)"));
                mListData.add(new CRMDetailBean(9, "机会类型", -1));
                mListData.add(new CRMDetailBean(11, "机会来源", -1));
                mListData.add(new CRMDetailBean(6, "备注", ""));
                break;
            case 4:
                mTvTitle.setText("新建机会");
                mListData.add(new CRMDetailBean(1, "基本信息(必填)"));
                mListData.add(new CRMDetailBean("机会名称", "", 1));
                mListData.add(new CRMDetailBean("销售金额", "", 1));
                mListData.add(new CRMDetailBean(7, "销售阶段", 0));
                mListData.add(new CRMDetailBean(8, "结单日期", 0));
                mListData.add(new CRMDetailBean(10, "联系人", 0));

                mListData.add(new CRMDetailBean(1, "其他信息(选填)"));
                mListData.add(new CRMDetailBean(9, "机会类型", -1));
                mListData.add(new CRMDetailBean(11, "机会来源", -1));
                mListData.add(new CRMDetailBean(6, "备注", ""));
                break;
            case 5:
                mTvTitle.setText("编辑机会");
                mChanceId = intent.getStringExtra("chance_id");
                mCrmChanceBean = (CRMChanceBean) intent.getSerializableExtra("crm_data");
                mListData.add(new CRMDetailBean(1, "基本信息(必填)"));
                mListData.add(new CRMDetailBean("机会名称", mCrmChanceBean.getChance_name(), 1));
                int stage = mCrmChanceBean.getMarket_stage();
                String time = mCrmChanceBean.getStatement_date();
                if (stage == 5){
                    mListData.add(new CRMDetailBean("销售金额", true,mCrmChanceBean.getMarket_amount()));
                    mListData.add(new CRMDetailBean("销售阶段", true,CRMTextSelectActivity.stage[stage]));

                    if (time.length() == 10) {
                        date = Long.parseLong(time) * 1000;
                        mListData.add(new CRMDetailBean("结单日期",true, DateUtil.formatDate(date)));
                    } else {
                        date = Long.parseLong(time);
                        mListData.add(new CRMDetailBean("结单日期",true, DateUtil.formatDate(date)));
                    }
                }else{
                    mListData.add(new CRMDetailBean("销售金额", mCrmChanceBean.getMarket_amount()));
                    mListData.add(new CRMDetailBean(7, "销售阶段", stage));
                    if (time.length() == 10) {
                        date = Long.parseLong(time) * 1000;
                        mListData.add(new CRMDetailBean(8,"结单日期", DateUtil.formatDate(date)));
                    } else {
                        date = Long.parseLong(time);
                        mListData.add(new CRMDetailBean(8,"结单日期", DateUtil.formatDate(date)));
                    }
                }
                if (mCrmChanceBean.getClues().size() > 0) {
                    CRMLibraryListData base = mCrmChanceBean.getClues().get(0);
                    mListData.add(new CRMDetailBean("联系人",true, base.getName()));
                }
                mListData.add(new CRMDetailBean(1, "其他信息(选填)"));
                mListData.add(new CRMDetailBean(9, "机会类型", mCrmChanceBean.getChance_type()));
                mListData.add(new CRMDetailBean(11, "机会来源", mCrmChanceBean.getChance_source()));
                mListData.add(new CRMDetailBean(6, "备注", mCrmChanceBean.getRemark()));
                break;

            case 6:
                mTvTitle.setText("新建客户");
                mListData.add(new CRMDetailBean(1, "基本信息(必填)"));
                mListData.add(new CRMDetailBean("客户名称", "", 1));
                mListData.add(new CRMDetailBean(4, 1, "地址", ""));

                mListData.add(new CRMDetailBean(1, "联系信息(必填)"));
                mListData.add(new CRMDetailBean(10, "联系人", 0));

                mListData.add(new CRMDetailBean(1, "其他信息(选填)"));
                mListData.add(new CRMDetailBean("传真", ""));
                mListData.add(new CRMDetailBean("网站", ""));
                mListData.add(new CRMDetailBean("微博", ""));
                mListData.add(new CRMDetailBean(14, "行业", -1));
                mListData.add(new CRMDetailBean("总人数", ""));
                mListData.add(new CRMDetailBean(15, "客户级别", -1));
                mListData.add(new CRMDetailBean(6, "备注", ""));
                mListData.add(new CRMDetailBean(-1, ""));
                break;
            case 7:
                mTvTitle.setText("转成我的客户");
                mTvRight.setText("转换");
                mChanceId = intent.getStringExtra("chance_id");
                mListData.add(new CRMDetailBean(1, "基本信息(必填)"));
                mListData.add(new CRMDetailBean("客户名称", "", 1));
                mListData.add(new CRMDetailBean(4, 1, "地址", ""));
                mListData.add(new CRMDetailBean("销售机会", intent.getStringExtra("chance_name")));

                mListData.add(new CRMDetailBean(1, "其他信息(选填)"));
                mListData.add(new CRMDetailBean("传真", ""));
                mListData.add(new CRMDetailBean("网站", ""));
                mListData.add(new CRMDetailBean("微博", ""));
                mListData.add(new CRMDetailBean(14, "行业", -1));
                mListData.add(new CRMDetailBean("总人数", ""));
                mListData.add(new CRMDetailBean(15, "客户级别", -1));
                mListData.add(new CRMDetailBean(6, "备注", ""));
                mListData.add(new CRMDetailBean(-1, ""));
                break;
        }

        if (mListData.size() > 0) {
            mAdapter = new CRMEditAdapter(mActivity, mListData);
            mListView.setAdapter(mAdapter);
        }

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CRMDetailBean bean = mListData.get(position);
                if (bean.getType() == 2) {
                    Intent sex = new Intent(mActivity, CRMTextSelectActivity.class);
                    sex.putExtra("action_select", 2);
                    sex.putExtra("index", bean.getIndex());
                    startActivityForResult(sex, SELECT_STATUS);

                } else if (bean.getType() == 3) {
                    Intent sex = new Intent(mActivity, CRMTextSelectActivity.class);
                    sex.putExtra("action_select", 3);
                    sex.putExtra("index", bean.getIndex());
                    startActivityForResult(sex, SELECT_SEX);

                } else if (bean.getType() == 5) {
                    Intent source = new Intent(mActivity, CRMTextSelectActivity.class);
                    source.putExtra("action_select", 5);
                    source.putExtra("index", bean.getIndex());
                    startActivityForResult(source, SELECT_SOURCE);

                } else if (bean.getType() == 6) {
                    Intent remark = new Intent(mActivity, CRMRemarkActivity.class);
                    remark.putExtra("action_type", 1);
                    remark.putExtra("crm_remark", bean.getContent());
                    startActivityForResult(remark, SELECT_REMARK);
                } else if (bean.getType() == 7) {
                    Intent source = new Intent(mActivity, CRMTextSelectActivity.class);
                    source.putExtra("action_select", 7);
                    source.putExtra("index", bean.getIndex());
                    startActivityForResult(source, SELECT_STAGE);

                } else if (bean.getType() == 8) {
                    selectDateDialog();
                } else if (bean.getType() == 9) {
                    Intent type = new Intent(mActivity, CRMTextSelectActivity.class);
                    type.putExtra("action_select", bean.getType());
                    type.putExtra("index", bean.getIndex());
                    startActivityForResult(type, SELECT_CHANCE_TYPE);

                } else if (bean.getType() == 11) {
                    Intent source = new Intent(mActivity, CRMTextSelectActivity.class);
                    source.putExtra("action_select", bean.getType());
                    source.putExtra("index", bean.getIndex());
                    startActivityForResult(source, SELECT_CHANCE_SOURCE);

                } else if (bean.getType() == 10) {
                    Intent create = new Intent(CRMCreateEditActivity.this, CRMCreateEditActivity.class);
                    create.putExtra("action_type", 1);
                    create.putExtra("group_id", mGroupId);
                    create.putExtra("type", mType);
                    startActivityForResult(create, SELECT_CONTACT);
                } else if (bean.getType() == 14) {
                    Intent source = new Intent(mActivity, CRMTextSelectActivity.class);
                    source.putExtra("action_select", bean.getType());
                    source.putExtra("index", bean.getIndex());
                    startActivityForResult(source, SELECT_INDUSTRY);
                } else if (bean.getType() == 15) {
                    Intent source = new Intent(mActivity, CRMTextSelectActivity.class);
                    source.putExtra("action_select", bean.getType());
                    source.putExtra("index", bean.getIndex());
                    startActivityForResult(source, SELECT_CLIENT_LEVEL);
                }
            }
        });

        c = Calendar.getInstance();
        curYear = c.get(Calendar.YEAR);
        curMonth = c.get(Calendar.MONTH) + 1; //通过Calendar算出的月数要+1
        curDate = c.get(Calendar.DATE);


    }

    /**
     * 创建、编辑公海
     *
     * @param map
     */
    private void createPublicCRM(HashMap<String, String> map) {

        String name = map.get("姓名");
        String phone = map.get("手机");
        String number = map.get("电话");
        String email = map.get("邮箱");
        if (StringUtil.isEmpty(name)) {
            Toast.makeText(CRMCreateEditActivity.this, "姓名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!StringUtil.isMobile(phone)) {
            Toast.makeText(CRMCreateEditActivity.this, "手机号码不正确", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!StringUtil.isEmpty(number) && !StringUtil.checkPhone(number)) {
            Toast.makeText(CRMCreateEditActivity.this, "电话号码不正确", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!StringUtil.isEmpty(email) && !StringUtil.checkEmail(email)) {
            Toast.makeText(CRMCreateEditActivity.this, "邮箱格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        if (mFlag == 2) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLUE_ID, mClueId));
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_NAME, name));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_NEW_PHONE, phone));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SEX, map.get("性别")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_COMPANY, map.get("公司")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEPARTMENT, map.get("部门")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_JOB, map.get("职务")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TELEPHONE, number));

        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_EMAIL, email));
        if (!StringUtil.isEmpty(map.get("地址"))) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ADDRESS, map.get("地址")));
            if (mAddressBean != null) {
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LONGITUDE, mAddressBean.getLongitude() + ""));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LATITUDE, mAddressBean.getLatitude() + ""));
            }
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ADDRESS, map.get("地址")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CODE, map.get("邮编")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_REMARK, map.get("备注")));
        if (!"-1".equals(map.get("线索来源"))) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ORIGIN, map.get("线索来源")));
        }


        CRMCreateMsg msg = null;
        if (mFlag == 1) {
            if (mType == 2 && !StringUtil.isEmpty(mChanceId)) {
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TYPE, mType + ""));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_OBJ_ID, mChanceId));
            }
            msg = new CRMCreateMsg(mHandler.obtainMessage(CREATE_PUBLIC_CRM), name, phone);
            msg.mApi = AsynHttpClient.API_CRM_PUBLIC_CREATE;
        } else if (mFlag == 2) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STATUS, map.get("跟进状态")));
            msg = new CRMCreateMsg(mHandler.obtainMessage(EDIT_PUBLIC_CRM));
            msg.mApi = AsynHttpClient.API_CRM_BASE_EDIT;
        }
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCRMHttp(msg);

    }

    /**
     * 线索转为销售机会
     *
     * @param map
     */
    private void toChanceCRM(HashMap<String, String> map) {

        String chanceName = map.get("机会名称");
        String marketAmount = map.get("销售金额");
        String marketStage = map.get("销售阶段");
        String statementDate = date / 1000 + "";
        String contactName = map.get("联系人");
        if (StringUtil.isEmpty(chanceName)) {
            Toast.makeText(CRMCreateEditActivity.this, "机会名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isEmpty(marketAmount)) {
            Toast.makeText(CRMCreateEditActivity.this, "销售金额不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isEmpty(marketStage) || "0".equals(marketStage)) {
            Toast.makeText(CRMCreateEditActivity.this, "销售阶段不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (StringUtil.isEmpty(statementDate) || "0".equals(statementDate)) {
            Toast.makeText(CRMCreateEditActivity.this, "结单日期不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isEmpty(contactName)) {
            Toast.makeText(CRMCreateEditActivity.this, "请先选择机会联系人,再创建机会", Toast.LENGTH_SHORT).show();
            return;
        }
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        if (mFlag == 5 && !StringUtil.isEmpty(mChanceId)) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_ID, mChanceId));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLUE_ID, mClueId));
        }

        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_NAME, chanceName));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MARKET_AMOUNT, marketAmount));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MARKET_STAGE, marketStage));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STATEMENT_DATE, statementDate));
        if (!"-1".equals(map.get("机会类型"))) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_TYPE, map.get("机会类型")));

        }
        if (!"-1".equals(map.get("机会来源"))) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_SOURCE, map.get("机会来源")));
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_REMARK, map.get("备注")));

        CRMCreateMsg msg = null;
        if (mFlag == 5) {
            msg = new CRMCreateMsg(mHandler.obtainMessage(EDIT_CHANCE_CRM));
            msg.mApi = AsynHttpClient.API_CRM_CHANCE_UPDATE;
        } else {
            msg = new CRMCreateMsg(mHandler.obtainMessage(TO_CHANCE_CRM));
            msg.mApi = AsynHttpClient.API_CRM_CHANCE_CONVERT;

        }
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCRMHttp(msg);

    }

    private void createClientCRM(HashMap<String, String> map) {

        String name = map.get("客户名称");
        String loction = map.get("地址");
        String contactName = map.get("联系人");

        if (StringUtil.isEmpty(name)) {
            Toast.makeText(CRMCreateEditActivity.this, "客户名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isEmpty(loction)) {
            Toast.makeText(CRMCreateEditActivity.this, "地址不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isEmpty(contactName)) {
            Toast.makeText(CRMCreateEditActivity.this, "请先选择客户联系人,再创建客户", Toast.LENGTH_SHORT).show();
            return;
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLUE_ID, mClueId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLIENT_NAME, name));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ADDRESS, map.get("地址")));
        if (mAddressBean != null) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LONGITUDE, mAddressBean.getLongitude() + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LATITUDE, mAddressBean.getLatitude() + ""));
        }

        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_FAX, map.get("传真")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SITE, map.get("网站")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEIBO, map.get("微博")));
        if (!"-1".equals(map.get("行业"))) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TRADE, map.get("行业")));
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MEMBER_COUNT, map.get("总人数")));
        if (!"-1".equals(map.get("客户级别"))) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLIENT_LEVEL, map.get("客户级别")));
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_REMARK, map.get("备注")));

        CRMCreateMsg msg = new CRMCreateMsg(mHandler.obtainMessage(CREATE_CLIENT_CRM));
        msg.mApi = AsynHttpClient.API_CRM_CLIENT_CREATE;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCRMHttp(msg);

    }

    private void convertClientCRM(HashMap<String, String> map) {

        String name = map.get("客户名称");
        String loction = map.get("地址");

        if (StringUtil.isEmpty(name)) {
            Toast.makeText(CRMCreateEditActivity.this, "客户名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isEmpty(loction)) {
            Toast.makeText(CRMCreateEditActivity.this, "地址不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_ID, mChanceId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLIENT_NAME, name));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ADDRESS, map.get("地址")));
        if (mAddressBean != null) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LONGITUDE, mAddressBean.getLongitude() + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LATITUDE, mAddressBean.getLatitude() + ""));
        }

        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_FAX, map.get("传真")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SITE, map.get("网站")));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEIBO, map.get("微博")));
        if (!"-1".equals(map.get("行业"))) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TRADE, map.get("行业")));
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MEMBER_COUNT, map.get("总人数")));
        if (!"-1".equals(map.get("客户级别"))) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLIENT_LEVEL, map.get("客户级别")));
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_REMARK, map.get("备注")));

        CRMCreateMsg msg = new CRMCreateMsg(mHandler.obtainMessage(CONVERT_CLIENT_CRM));
        msg.mApi = AsynHttpClient.API_CRM_CLIENT_CONVERT;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCRMHttp(msg);

    }


    @Override
    public void onClick(View v) {
        if (Constants.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.title_ll_back:
                if (mFlag == 7) {
                    showNoticeDlg(0, "放弃将机会转成客户,销售阶段\n不可以调整为赢单");
                } else {
                    finish();
                }
                break;
            case R.id.title_tv_right:
                hashMap.clear();
                for (int i = 0; i < mListData.size(); i++) {
                    CRMDetailBean bean = mListData.get(i);
                    if (bean.getType() != 1 && !StringUtil.isEmpty(bean.getTitle())) {
                        if (bean.getType() == 0 || bean.getType() == 4 || bean.getType() == 6) {
                            hashMap.put(bean.getTitle(), bean.getContent());
                        } else if (bean.getType() == 10) {
                        } else {
                            hashMap.put(bean.getTitle(), bean.getIndex() + "");
                        }
                    }
                }
                switch (mFlag) {
                    case 1:
                    case 2:
                        createPublicCRM(hashMap);
                        break;
                    case 3:
                    case 4:
                    case 5:
                        toChanceCRM(hashMap);
                        break;
                    case 6:
                        createClientCRM(hashMap);
                        break;
                    case 7:
                        convertClientCRM(hashMap);
                        break;

                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SELECT_STATUS:
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 2) {
                            mListData.get(i).setIndex(data.getIntExtra("index", 0));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case SELECT_SEX:
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 3) {
                            mListData.get(i).setIndex(data.getIntExtra("index", 0));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case SELECT_SOURCE:
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 5) {
                            mListData.get(i).setIndex(data.getIntExtra("index", 0));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case SELECT_REMARK:
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 6) {
                            mListData.get(i).setContent(data.getStringExtra("crm_remark"));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case SELECT_STAGE:
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 7) {
                            mListData.get(i).setIndex(data.getIntExtra("index", 0));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case SELECT_CHANCE_TYPE:
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 9) {
                            mListData.get(i).setIndex(data.getIntExtra("index", 0));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case SELECT_CHANCE_SOURCE:
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 11) {
                            mListData.get(i).setIndex(data.getIntExtra("index", 0));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case SELECT_INDUSTRY:
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 14) {
                            mListData.get(i).setIndex(data.getIntExtra("index", 0));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case SELECT_CLIENT_LEVEL:
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 15) {
                            mListData.get(i).setIndex(data.getIntExtra("index", 0));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case GET_LOCCTION:
                    if (mAddressBean == null) {
                        mAddressBean = new AddressData();
                    }
                    mAddressBean.setLatitude(data.getDoubleExtra("latitude", 0));
                    mAddressBean.setLongitude(data.getDoubleExtra("longitude", 0));
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 4) {
                            mListData.get(i).setContent(data.getStringExtra("address"));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case SELECT_CONTACT:
                    mTvRight.setText("保存");
                    mFlag = data.getIntExtra("action_type", 1);
                    if (mFlag == 4) {
                        mTvTitle.setText("新建机会");
                    } else if (mFlag == 6) {
                        mTvTitle.setText("新建客户");
                    }
                    mClueId = data.getStringExtra("clue_id");
                    for (int i = 0; i < mListData.size(); i++) {
                        if (mListData.get(i).getType() == 10) {
                            mListData.get(i).setType(0);
                            mListData.get(i).setContent(data.getStringExtra("contact_name"));
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
            }
        }
    }

    /**
     * 更新数据
     *
     * @param position
     * @param text
     */
    public void updateView(int position, String text) {
        mListData.get(position).setContent(text);
    }

    /**
     * 设置地址
     *
     * @param loction
     */
    public void setLoction(String loction) {
        Intent intent = new Intent(mActivity, BaiduMapActivity.class);
        if (mAddressBean == null) {
            LatLng geoPointBystr = LocationUtil.getGeoPointBystr(loction, mActivity);
            if (geoPointBystr != null) {
                intent.putExtra("address", loction);
                intent.putExtra("latitude", geoPointBystr.latitude);
                intent.putExtra("longitude", geoPointBystr.longitude);
                intent.setAction("CRM_update");
                Log.d("getLoction", "value: " + geoPointBystr.toString());
            } else {
                intent.setAction("CRM_null");
            }
        } else {
            intent.putExtra("address", loction);
            intent.putExtra("latitude", mAddressBean.getLatitude());
            intent.putExtra("longitude", mAddressBean.getLongitude());
            intent.setAction("CRM_update");
        }
        startActivityForResult(intent, GET_LOCCTION);

    }

    /**
     * 初始化年
     */
    private void initYear(WheelView wheelView, int curYear) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, curYear, curYear);
        numericWheelAdapter.setLabel(" 年");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        wheelView.setViewAdapter(numericWheelAdapter);
        wheelView.setCyclic(false);
    }

    /**
     * 初始化月
     */
    private void initMonth(WheelView wheelView) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 1, 12, "%02d");
        numericWheelAdapter.setLabel(" 月");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        wheelView.setViewAdapter(numericWheelAdapter);
        wheelView.setCyclic(true);
        wheelView.addScrollingListener(scrollListener);
    }

    /**
     * 初始化天
     */
    private void initDay(WheelView wheelView, int arg1, int arg2) {
        int count = Constants.getDay(arg1, arg2);
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 1, count, "%02d");
        numericWheelAdapter.setLabel(" 日");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        wheelView.setViewAdapter(numericWheelAdapter);
        wheelView.setCyclic(true);
        // TODO 如果之前选择的日期大于这个月的天数 置为第一天
        if (wheelView.getCurrentItem() + 1 > count) {
            wheelView.setCurrentItem(0);
        }
    }

    /**
     * 当年份或者月份滑动结束时要更新 天数
     */
    OnWheelScrollListener scrollListener = new OnWheelScrollListener() {

        @Override
        public void onScrollingStarted(WheelView wheel) {

        }

        @Override
        public void onScrollingFinished(WheelView wheel) {
            // TODO Auto-generated method stub
            int n_year = curYear;
            int n_month = month.getCurrentItem() + 1;
            initDay(day, n_year, n_month);
        }
    };

    /**
     * 选择日期
     */
    private void selectDateDialog() {

        final AlertDialog dialog = new AlertDialog.Builder(mActivity)
                .create();
        dialog.show();
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.dimAmount = 0.3f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha = 0.5f; // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.ap_date_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.bottomStyle);


        year = (WheelView) window.findViewById(R.id.new_year);
        initYear(year, curYear);
        month = (WheelView) window.findViewById(R.id.new_month);
        initMonth(month);
        day = (WheelView) window.findViewById(R.id.new_day);
        initDay(day, curYear, curMonth);
        WheelView morning_After = (WheelView) window.findViewById(R.id.new_m_a);
        morning_After.setVisibility(View.GONE);

        // 设置当前时间
        year.setCurrentItem(0);
        month.setCurrentItem(curMonth - 1);
        day.setCurrentItem(curDate - 1);

        // 设置监听
        TextView ok = (TextView) window.findViewById(R.id.new_set);
        TextView cancel = (TextView) window.findViewById(R.id.new_cancel);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                c.set(curYear, month.getCurrentItem(), day.getCurrentItem() + 1, 0, 0, 00);
                for (int i = 0; i < mListData.size(); i++) {
                    if (mListData.get(i).getType() == 8) {
                        date = c.getTimeInMillis();
                        mListData.get(i).setContent(DateUtil.formatDate(c.getTimeInMillis()));
                        mAdapter.notifyDataSetChanged();
                        break;
                    }
                }
                dialog.cancel();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.cancel();
            }
        });
        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.view_cancel);
        cancelLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                dialog.cancel();
                return false;
            }
        });
    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = AllDialogUtil.getInstance(mActivity).waitDialog();
//            mProgressDialog.setCancelable(false);
            if (!mWaitDialog.isShowing()) {
                mWaitDialog.show();
            }
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    /**
     * @param flag 0:销售机会转为客户点击返回键   1:销售机会转为客户成功
     * @param msg
     */
    public void showNoticeDlg(final int flag, String msg) {
        String okText = mActivity.getString(R.string.label_btn_ok);
        String cancelText = mActivity.getString(R.string.cancel);
        mDialogUtil.titleMsgBtnStyle("提示", msg, okText);
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                if (flag == 0) {
                    finish();
                } else if (flag == 1) {
                    setResult(RESULT_OK);
                    finish();
                }
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();

            }
        });
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mFlag == 7) {
            showNoticeDlg(0, "放弃将机会转成客户,销售阶段\n不可以调整为赢单");
        } else {
            finish();
        }
    }
}
